package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 刘付磊
 * @date 2021/11/18 0018
 */
@Service
@Slf4j
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void saveComments(String movementId, String comment) {
        //1.获取操作用户id
        Long userId = UserHolder.getUserId();
        //2.构造comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //3.调用api保存评论
        Integer commentCount = commentApi.save(comment1);
        log.info("commentCount" + commentCount);
    }

    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //1.调用api查询评论列表
        List<Comment> list = commentApi.findComments(page, pagesize, movementId, CommentType.COMMENT);
        //2.判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3.如果存在提取所有用户id，调用userinfoApi查询用户详情
        List<Long> userId = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userId, null);
        //4.构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        //5.构造返回值
        return new PageResult(page, pagesize, 0, vos);
    }

    public Integer likeCovement(String movementId) {
        //1.调用aip查询用户是否点赞
        Boolean haslike = commentApi.haveCovement(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //2.如果已经点赞 抛出异常
        if (haslike) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3.调用api保存数据到mongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());;
        Integer count = commentApi.save(comment);
        //4.拼接redis的key，将用户点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY+movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY+UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    public Integer dislikeCovement(String movementId) {
        //1.调用api查看用户是否已点赞

        Boolean haveCovement = commentApi.haveCovement(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //2.如果未点赞，抛出异常
        if(!haveCovement){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3.调用api，删除数据，返回点赞数量
        Comment comment  = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.remove(comment);
        //4.拼接rediskey 删除点赞缓存
        String key = Constants.MOVEMENTS_INTERACT_KEY+movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY+UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
    //喜欢
    public Integer loveCovement(String movementId) {
        //1.调用aip查询用户是否点赞
        Boolean haslike = commentApi.haveCovement(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //2.如果已经点赞 抛出异常
        if (haslike) {
            throw new BusinessException(ErrorResult.loveError());
        }
        //3.调用api保存数据到mongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());;
        Integer count = commentApi.save(comment);
        //4.拼接redis的key，将用户点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY+movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY+UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }
    //取消喜欢
    public Integer unloveCovement(String movementId) {
        //1.调用api查看用户是否已点赞

        Boolean haveCovement = commentApi.haveCovement(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //2.如果未点赞，抛出异常
        if(!haveCovement){
            throw new BusinessException(ErrorResult.disloveError());
        }
        //3.调用api，删除数据，返回点赞数量
        Comment comment  = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.remove(comment);
        //4.拼接rediskey 删除点赞缓存
        String key = Constants.MOVEMENTS_INTERACT_KEY+movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY+UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }
}
